package gosu;

import java.awt.font.LineMetrics;
import javax.media.opengl.GL;
import javax.media.opengl.glu.GLU;
import com.sun.opengl.util.j2d.TextRenderer;

public class FontDrawOp extends DrawOp {
  private Window _window;
  private TextRenderer _renderer;
  private String _text;
  private double _x;
  private double _y;
  private double _z;
  private double _factorX;
  private double _factorY;
  private java.awt.Color _color;
  private int _mode;
  private int _numArgs;
  private double _angle;


  public FontDrawOp(Window window, TextRenderer renderer, String text, double x, double y, double z) {
    _window = window;
    _renderer = renderer;
    _text = text;
    _x = x;
    _y = _window.getHeight() - y;
    _z = z;
    _factorX = 1.0;
    _factorY = 1.0;
    _color = java.awt.Color.white;
    _numArgs = 4;
  }


  public FontDrawOp(Window window, TextRenderer renderer, String text, double x, double y, double z, double factorX, double factorY) {
    this(window, renderer, text, x, y, z);
    _factorX = factorX;
    _factorY = factorY;
    _numArgs = 6;
  }


  public FontDrawOp(Window window, TextRenderer renderer, String text, double x, double y, double z, double factorX, double factorY, Color c, int mode) {
    this(window, renderer, text, x, y, z, factorX, factorY);
    _color = c.getAWTColor();
    _mode = mode;
    _numArgs = 8;
  }

  public void setAngle(double angle) { _angle = angle; }


  public double getZ() { return _z; }


  public void execute() {
    GL gl = GLU.getCurrentGL();

    _renderer.beginRendering(_window.getWidth(), _window.getHeight());

    if (_mode == Image.ADDITIVE) {
      gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
    } else {
      gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
    }

    _renderer.setColor(_color);

    gl.glMatrixMode(GL.GL_MODELVIEW);

    gl.glTranslated(_x, _y, 0);
    gl.glRotated(_angle, 0, 0, -1);
    gl.glTranslated(-_x, -_y, 0);

    gl.glScaled(_factorX, _factorY, 1.0);

    LineMetrics metrics = _renderer.getFont().getLineMetrics(_text, _renderer.getFontRenderContext());
    _renderer.draw(_text, (int) (_x / _factorX), (int) ((_y / _factorY)  - (_renderer.getFont().getSize() - metrics.getDescent())));

    _renderer.endRendering();
  }
}
